package org.shanyu.tide.service;

import org.shanyu.tide.mapper.*;
import org.shanyu.tide.model.RedEnvelop;
import org.shanyu.tide.model.RedEnvelopPartition;
import org.shanyu.tide.utils.JsonResult;
import org.shanyu.tide.utils.RedEnvelopUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class RedEnvelopService {

    @Autowired
    RedEnvelopMapper redEnvelopMapper;

    @Autowired
    RedEnvelopPartitionMapper redEnvelopPartitionMapper;

    @Transactional(rollbackFor = Exception.class)
    public JsonResult<String> AddRedEnvelop(RedEnvelop redEnvelop) throws Exception {
        Integer totalAmount = 10;
        List<Integer> redEnvelopPartitionlist = RedEnvelopUtil.divideRedPackage(totalAmount,redEnvelop.getSendCount());
        redEnvelopMapper.insert(redEnvelop);

        Integer redEnvelopId = 1;
        for (Integer item: redEnvelopPartitionlist) {
            RedEnvelopPartition partition = new RedEnvelopPartition();
            partition.setMoney(Double.valueOf(item));
            partition.setRedEnvelopId(redEnvelopId);
            partition.setCreatedTime(new Date());
            partition.setUpdatedTime(new Date());
            redEnvelopPartitionMapper.insert(partition);
        }

        return JsonResult.success("操作成功！");
    }

}
